<?php
namespace app\home\controller;

use \app\common\controller\Homebase;
use think\Log;
use \think\Request;
use \think\Loader;
use \think\Validate;
use \think\Db;
use \think\Session;
use \thans\Ret;

class Auth extends Basic
{
	public function _initialize()
	{
		$this->auth = Loader::model('Auth');
		$this->authRecord = Loader::model('AuthRecord');
		$this->recycleBin = Loader::model('RecycleBin');
        $arr[0]['text']='权限组列表';
        $arr[0]['url']='index';
        $this->assign('third_menu', $arr);
	}
    /**
     * 权限组列表
     * @return [type] [description]
     */
	public function index()
	{
		$list = $this->auth->paginate(10);
		$this->assign('list', $list);
		return $this->fetch();
	}
    /**
     * 权限组增加表单
     */
	public function add()
	{
		if(input('id')) {
			$list = $this->auth->where('auth_id', input('id'))->find()->toArray();
			$this->assign('data', $list);
		}
		return $this->fetch();
	}
    /**
     * 权限组增加提交
     * @return [type] [description]
     */
	public function goAdd()
	{
        
		$data['auth_name'] = input('auth_name');
		$data['auth_remark'] = input('auth_remark');
		if(input('auth_status')) {
			$data['auth_status'] = 1;
		} else {
			$data['auth_status'] = 0;
		}
		if($data['auth_name'] == "") {
            return $this->ret->setCode(1)->setMsg('部门名称不能为空')->toJson();
		}
		if(input('id')) {
			$data['auth_up_time'] = date('Y-m-d H:i:s', time());
			$res = $this->auth->where('auth_id', input('id'))->update($data);
			if($res) {
                return $this->ret->setMsg('修改成功!')->setReload()->toJson();
			} else {
                return $this->ret->setCode(2)->setMsg('修改失败')->toJson();
			}
		} else {
			$data['auth_addtime'] = date('Y-m-d H:i:s', time());
			$id = $this->auth->insertGetId($data);
			if($id) {
                return $this->ret->setMsg('新增成功!')->setReload()->toJson();
			} else {
                return $this->ret->setCode(3)->setMsg('新增失败')->toJson();
			}
		}
	}
    /**
     * 权限组删除
     * @return [type] [description]
     */
	public function auth_del()
	{
        
	    $where = array('auth_id' => input('id'));
		$list = $this->auth->where($where)->find();

        $result = $this->recycleBin->cutout(
            $this->auth,
            $list,
            $where
        );

        if($result) {
            return $this->ret->setMsg('删除成功!')->setReload()->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg('删除失败')->toJson();
        }
	}

	/**
     * @name 权限设置
     * @date   2017.1.19
     */
	public function auth_edit()
    {
        $id = input('id');
        if (IS_POST){
            $this->menu = Loader::model('Menu');
            $menuids = isset($_POST['menuid']) ? $_POST['menuid'] : array();

            $menuids = is_array($menuids) ? $menuids : array();
            $recordIds   = array();
            foreach ($menuids as $menuid) {
                $menu = $this->menu->where(array('id' => intval($menuid)))->field('id,model,controller,action,name,data')->find();
                if ($menu) {
                    $model = $menu['model'];
                    $controller = $menu['controller'];
                    $action = $menu['action'];
                    $data = $menu['data'];
                    $name = strtolower("{$model}/{$controller}/{$action}");
                    $names[] = $name;
                    $currentRecord = $this->authRecord->where(array('auth_id' => $id, 'rule_value' => $name,'data'=>$data))->find();
                    if(!$currentRecord){
                        $recordIds[] = $this->authRecord->insertGetId(array('auth_id' => $id, 'rule_value' => $name, 'data' => $data, 'menu_id'=>$menu['id']));
                    }else{
                        $recordIds[] = $currentRecord->id;
                    }
                }
            }
            //  取出当前用户所有菜单权限
            $rule_values = $this->authRecord->ruleValue($id)->all();
            //  开始筛选不存在的权限并删除
            foreach ($rule_values as $rule_value){
                if(!in_array($rule_value['id'],$recordIds)){
                    $rule_value->delete();
                }
            }
            return $this->ret->setMsg('修改成功!')->setReload()->toJson();
        }
        return $this->ret->setCode(1)->setMsg('删除失败')->toJson();
	}

    /**
     * @name   权限列表展示
     * @date   2017.1.19
     */
	public function auth_index(){
        $id = input('id');
        $this->assign("id",$id);
        $this->menu = Loader::model('Menu');
        //拉取所有菜单
        $result = $this->menu->where('type',"in","0,1")->select();
        $newmenus  = array();
        $records = $this->authRecord->ruleValue($id)->all();
        $priv_data =array();
        foreach ($records as $record){
            $priv_data[] = $record['data'] ? $record['rule_value'].'/'.$record['data'] : $record['rule_value'];
        }
        foreach ($result as $m){
            $newmenus[$m['id']]=$m;
        }
        //$newResult = array();
        foreach ($result as $n => $t) {
            $result[$n]['checked'] = ($this->_is_checked($t, $id, $priv_data)) ? ' checked' : '';
            $result[$n]['level'] = $this->_get_level($t['id'], $newmenus);
            $result[$n]['style'] = empty($t['menu_pid']) ? '' : 'display:none;';
            $result[$n]['parentid_node'] = ($t['menu_pid']) ? ' class="child-of-node-' . $t['menu_pid'] . '"' : '';
            $result[$n]['parent_id'] = $t['menu_pid'];
            // orm传入tree中时会出现无法创建变量
            //$newResult[$t['id']] = $result[$n]->toArray();
        }
        Log::write("Result:".json_encode($result));
        $menu = new \thans\Common\tree($result);
        $menu->formatArrayForTree('id', 'menu_pid','name');
        $categorys = $menu->get_tree_array(0, '');

        $this->assign("list", $categorys);
        return $this->fetch();
    }

    /**
     *  检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param int $roleid 需要检查的角色ID
     */
    private function _is_checked($menu, $roleid, $priv_data) {

        $app=$menu['model'];
        $model=$menu['controller'];
        $action=$menu['action'];
        $data=$menu['data'];
        $name = $data ? strtolower("$app/$model/$action/$data") : strtolower("$app/$model/$action");
        if($priv_data){
            if (in_array($name, $priv_data)) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }

    }
    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0) {
        $array[$id]['parent_id'] = $array[$id]['menu_pid'];
        if ($array[$id]['menu_pid']==0 || empty($array[$array[$id]['menu_pid']]) || $array[$id]['menu_pid']==$id){
            return  $i;
        }else{
            $i++;
            $array[$id]['parent_id'] = $array[$id]['menu_pid'];
            return $this->_get_level($array[$id]['menu_pid'],$array,$i);
        }

    }
}
